package activity.LocalFile;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.TextView;

import com.hichip.campro.R;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.TimeZone;

import activity.FishEye.FishEyePhotoActivity;
import activity.ImagePagerActivity;
import activity.WallMounted.WallMountedPhotoActivity;
import base.HiFragment;
import bean.LeftLocalFileBean;
import bean.MyCamera;
import butterknife.BindView;
import butterknife.ButterKnife;
import common.HiDataValue;
import custom.stickygridview.GridItem;
import custom.stickygridview.StickyGridAdapter;
import custom.stickygridview.YMComparator;
import utils.SharePreUtils;

public class LocalPhotoFragment extends HiFragment implements AdapterView.OnItemClickListener {
    @BindView(R.id.sticky_gridview) GridView sticky_gridview;
    public StickyGridAdapter mAdapter;
    public ArrayList<GridItem> mGirdList=new ArrayList<>();
    private Map<String, Integer> sectionMap = new HashMap<String, Integer>();

    public  List<GridItem> mDeleteList = new ArrayList<GridItem>();
    private static int section = 1;
    private MyCamera mMyCamera;
    private DeleteBroadcastReceiver mReceiver;
    @BindView(R.id.tv_noting) TextView tv_noting;

    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view=View.inflate(getActivity(), R.layout.fragment_local_photo,null);
        ButterKnife.bind(this,view);
        initViewAndData(view);
        setListeners();
        registerReceiver();
        return view;
    }

    private void registerReceiver() {
        mReceiver=new DeleteBroadcastReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction(ImagePagerActivity.BROAD_ACTION);
        getActivity().registerReceiver(mReceiver,filter);
    }

    private void setListeners() {
        sticky_gridview.setOnItemClickListener(this);
    }

    private void initViewAndData(View view) {
        initData();
        if(mGirdList.size()<1){
            sticky_gridview.setVisibility(View.GONE);
            tv_noting.setVisibility(View.VISIBLE);
        }
        mAdapter = new StickyGridAdapter(getActivity(), mGirdList, sticky_gridview);
        sticky_gridview.setAdapter(mAdapter);
    }

    private  class DeleteBroadcastReceiver  extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(ImagePagerActivity.BROAD_ACTION)){
                int position = intent.getIntExtra(ImagePagerActivity.INDEX, 0);
                mGirdList.remove(position);
                mAdapter.notifyDataSetChanged();
                if(mGirdList.size()<1){
                    sticky_gridview.setVisibility(View.GONE);
                    tv_noting.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mReceiver!=null){
            getActivity().unregisterReceiver(mReceiver);
        }
    }

    private void initData() {
        Bundle bundle=getArguments();
        LeftLocalFileBean bean= (LeftLocalFileBean)bundle.getSerializable("bean");

        for(MyCamera camera:HiDataValue.CameraList){
            if(camera.getUid().equals(bean.getUid())){
                this.mMyCamera=camera;
                break;
            }
        }
        if(mMyCamera==null){
            //说明摄像机被删除了 所以这里随便new 一个
            mMyCamera=new MyCamera(getActivity(),getString(R.string.title_camera_fragment),bean.getUid(),"admin","admin");
            boolean isWallMounted=SharePreUtils.getBoolean(HiDataValue.CACHE,getActivity(),mMyCamera.getUid() + "isWallMounted");
            if(isWallMounted){
                mMyCamera.isWallMounted=true;
            }
            HiDataValue.DeleteCameraList.add(mMyCamera);
        }

        File folder=new File(bean.getFile().getAbsolutePath()+"/Snapshot/");
        if(folder!=null&&folder.exists()){
            File[] files=folder.listFiles();
            if(files.length>0){
                for(File file:files){
                    long times = file.lastModified() / 1000;
                    GridItem gridItem=new GridItem(file.getAbsolutePath(),paserTimeToYM(times));
                    mGirdList.add(gridItem);
                }
            }
        }
        Collections.sort(mGirdList, new YMComparator());
        for (ListIterator<GridItem> it = mGirdList.listIterator(); it.hasNext();) {
            GridItem mGridItem = it.next();
            String ym = mGridItem.getTime();
            if (!sectionMap.containsKey(ym)) {
                mGridItem.setSection(section);
                sectionMap.put(ym, section);
                section++;
            } else {
                mGridItem.setSection(sectionMap.get(ym));
            }
        }
    }


    private String paserTimeToYM(long time) {
        TimeZone tz = TimeZone.getDefault();
        TimeZone.setDefault(tz);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date(time * 1000L));
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < 0) return;
        if (mAdapter.getDelMode()==1) {
            CheckBox checkBox = (CheckBox) view.findViewById(R.id.grid_cb);
            checkBox.setChecked(checkBox.isChecked() ? false : true);
            if (checkBox.isChecked()) {
                mDeleteList.add(mGirdList.get(position));
            } else {
                mDeleteList.remove(mGirdList.get(position));
            }
            mAdapter.checks[position] = checkBox.isChecked();
        } else {
            Intent intent = new Intent();
            if (mMyCamera.isWallMounted) {
                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mMyCamera.getUid());
                intent.putExtra("photo_path", mGirdList.get(position).getPath());
                intent.putExtra("position", position);
                intent.setClass(getActivity(), WallMountedPhotoActivity.class);
                startActivity(intent);
                return;
            }
            if (mMyCamera.isFishEye()) {
                // 初始化鱼眼顶装和壁装的模式
                int num = SharePreUtils.getInt("mInstallMode", getActivity(), mMyCamera.getUid());
                mMyCamera.mInstallMode = num == -1 ? 0 : num;
                intent.setClass(getActivity(), FishEyePhotoActivity.class);
                intent.putExtra("photo_path", mGirdList.get(position).getPath());
                intent.putExtra("position", position);
            } else {
                intent.setClass(getActivity(), ImagePagerActivity.class);
            }
            intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mMyCamera.getUid());
            intent.putParcelableArrayListExtra(EXTRA_GIRDLST, mGirdList);
            intent.putExtra(EXTRA_POSITION, position);
            startActivityForResult(intent, ACTIVITY_RESULT_PHOTO_VIEW);
            getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_RESULT_PHOTO_VIEW) {
            if (resultCode == Activity.RESULT_OK) {
                Bundle bundle = data.getExtras();
                int position = bundle.getInt(ImagePagerActivity.INDEX);
                mGirdList.remove(position);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    public static final String EXTRA_GIRDLST = "girdlst";
    public static final String EXTRA_POSITION = "position";
    private static final int ACTIVITY_RESULT_PHOTO_VIEW = 10;
}
